//
//  ChineseSortSection.swift
//  SmoSky
//
//  Created by zhu xietong on 2018/5/28.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation


struct ChineseSortSections {
    
    public class Section {
        var name:String = ""
        var childs:[Section] = [Section]()
        var body:NSMutableDictionary? = nil
        var data:NSMutableDictionary{
            get{
                let obj = NSMutableDictionary()
                obj["name"] = name
                if childs.count > 0
                {
                    let list = childs.map { (one:Section) -> NSMutableDictionary in
                        return one.data
                    }
                    
                    obj["childs"] = list.mutable_array
                }
                if let bd = body
                {
                    obj["body"] = bd
                }
                return obj
            }
        }
    }
    
    static func create(names:[Any],mapObjects:[Any])->(Section,[String]){
    
        let sortedObj = ChineseString.returnSortChineseArray(names, objectArray: mapObjects) ?? NSMutableArray()
        
        var indexs = [String]()
        let root = Section()
        
        sortedObj.list { (one:ChineseString, i) in
            let py = one.pinYin ?? ""
            let content = one.string ?? ""
            let object = one.object ?? NSMutableDictionary()
            let Key = py.char(at: 0)
            
            
            let lever2 = Section()
            lever2.name = content
            lever2.body = object
            if !indexs.contains(Key)
            {
                
                
                let lever1 = Section()
                lever1.name = Key
                lever1.childs.append(lever2)
                
                root.childs.append(lever1)
                indexs.append(Key)
            }
            else{
                if let lever1 = root.childs.filter({ (section:Section) -> Bool in
                    return section.name == Key
                }).first
                {
                    lever1.childs.append(lever2)
                }
            }
        }
        return (root,indexs)
            
        
        
    }
}
